package com.ldl.exam.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/02 21:56:28
 */
public class CommonUtil {
    public static final String words = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public static final Random random = new Random();
    public static String random(int count) {
        if(count <= 0) return "";
        char[] chars = words.toCharArray();
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < count; i++) {
            int index = random.nextInt(chars.length);
            buffer.append(chars[index]);
        }
        return buffer.toString();
    }

    public static String md5ToBase64(String str) {
        if(null == str) {
            return "";
        }
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] digest = md5.digest(str.getBytes("UTF-8"));
            String value = Base64.getEncoder().encodeToString(digest);
            return value;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isEmpty(String str) {
        return null == str || "".equals(str.trim());
    }

    public static final SimpleDateFormat sdf = new SimpleDateFormat();
    public static String dateToString(Date d, String pattern) {
        sdf.applyPattern(pattern);
        return sdf.format(d);
    }
    public static Date stringToDate(String date, String pattern) {
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            throw new IllegalArgumentException("格式错误", e);
        }
    }

    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }


}
